<?php

namespace App\Services;

use App\Models\Category;

class CategoryService{

    /**
     * 通过pid获取分类
     * @param int $pid
     * @return array|mixed
     */
    public function getCategoriesByPid($pid = 0){
        $categories = $this->getCategoriesByCache();
        if ($pid == 0) return $categories;
        if (!empty($categories[$pid]['child'])){
            return $categories[$pid]['child'];
        }else{
            return [];
        }
    }
    /**
     * 从缓存中获取所有分类
     * @return array|mixed
     */
    protected function getCategoriesByCache(){
        if (\Cache::has('categories')) return \Cache::get('categories');
        return $this->setCategoriesCache();
    }

    /**
     * 写入所有分类并写入缓存
     * @return array|mixed
     */
    public function setCategoriesCache(){
        $resault_list = [];
        $collection = Category::getCategoryListByPid(0);
        if ($collection->isEmpty()) return [];
        $collection = $collection->toArray();

        foreach ($collection as $key => $item) {
            $child = Category::getCategoryListByPid($item['id']);
            if (!$child->isEmpty()){
                $item['child'] = $child->toArray();
            }
            $resault_list[$item['id']] = $item;
        }
        \Cache::forever('categories', $resault_list);

        return $resault_list;
    }
}